package com.horizon.im.imClient.clientHandler;

import com.horizon.im.common.bean.UserDTO;
import com.horizon.im.common.bean.msg.ProtoMsg;
import com.horizon.im.imClient.client.ClientSession;
import com.horizon.im.imClient.clientBuilder.HeartBeatMsgBuilder;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Slf4j
@ChannelHandler.Sharable
@Service("HeartBeatClientHandler")
public class HeartBeatClientHandler extends ChannelInboundHandlerAdapter {

    //心跳的时间间隔，单位为s，要远小于服务器端IdleStateHandler中的readIdle，大概是1/3的readIdle，
    //因为一个来回算两个HeartBeat,要算间隔，那么必定是去->回->再去这里面的间隔时间
    private static final int HEARTBEAT_INTERVAL = 50;
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ClientSession session = ClientSession.getSession(ctx);
        UserDTO user = session.getUser();
        HeartBeatMsgBuilder builder = new HeartBeatMsgBuilder(user, session);
        ProtoMsg.Message message = builder.buildMsg();

    }

    //使用定时器发送心跳
    public void heartBeat(ChannelHandlerContext ctx, ProtoMsg.Message heartBeatMsg) {
        ctx.executor().schedule(() -> {
            if(ctx.channel().isActive()) {
                log.info("发送heart_beat消息，toServer");
                ctx.writeAndFlush(heartBeatMsg);
                //递归调用
                heartBeat(ctx, heartBeatMsg);
            }
        }, HEARTBEAT_INTERVAL, TimeUnit.SECONDS);
    }
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //判断消息实例
        if (null == msg || !(msg instanceof ProtoMsg.Message))
        {
            super.channelRead(ctx, msg);
            return;
        }

        //判断类型
        ProtoMsg.Message pkg = (ProtoMsg.Message) msg;
        ProtoMsg.HeadType headType = pkg.getType();
        if (headType.equals(ProtoMsg.HeadType.HEART_BEAT))
        {

            log.info(" 收到回写的 HEART_BEAT  消息 from server");

            return;
        } else
        {
            super.channelRead(ctx, msg);

        }
    }
}
